const { User } = require('../models');
const VerificationCode = require('../models/VerificationCode');
const SystemConfig = require('../models/SystemConfig');
const { generateToken } = require('../utils/jwt');
const { sendVerificationCode, sendWelcomeEmail, sendPasswordResetSuccessEmail } = require('../utils/mailer');

// 获取邮箱验证状态
const getEmailVerificationStatus = async () => {
  const config = await SystemConfig.findOne({ 
    where: { key: 'emailVerificationEnabled' } 
  });
  return config ? config.value === 'true' : false;
};

// 注册用户
exports.register = async (req, res) => {
  try {
    const { email, password, verificationCode } = req.body;

    // 验证必填字段
    if (!email || !password) {
      return res.status(400).json({
        success: false,
        message: '请提供邮箱和密码'
      });
    }

    // 检查用户是否已存在
    const existingUser = await User.findOne({ where: { email } });
    if (existingUser) {
      return res.status(400).json({
        success: false,
        message: '该邮箱已被注册'
      });
    }

    // 检查是否需要邮箱验证
    const emailVerificationRequired = await getEmailVerificationStatus();

    // 如果需要邮箱验证，验证验证码
    if (emailVerificationRequired) {
      if (!verificationCode) {
        return res.status(400).json({
          success: false,
          message: '请提供验证码'
        });
      }

      const isCodeValid = await VerificationCode.verifyCode(email, verificationCode, 'register');
      if (!isCodeValid) {
        return res.status(400).json({
          success: false,
          message: '验证码无效或已过期'
        });
      }
    }

    // 创建用户
    const user = await User.create({
      email,
      password,
      isVerified: !emailVerificationRequired, // 如果不需要邮箱验证，则直接设置为已验证
      role: 'user'
    });

    // 生成JWT令牌
    const token = generateToken(user);

    // 发送欢迎邮件
    await sendWelcomeEmail(email);

    res.status(201).json({
      success: true,
      message: emailVerificationRequired ? '注册成功，请验证您的邮箱' : '注册成功',
      data: {
        user: {
          id: user.id,
          email: user.email,
          role: user.role,
          isVerified: user.isVerified,
          virtualCoins: user.virtualCoins
        },
        token,
        emailVerificationRequired
      }
    });
  } catch (error) {
    console.error('注册用户错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
};

// 发送注册验证码
exports.sendRegisterCode = async (req, res) => {
  try {
    const { email } = req.body;

    // 验证邮箱
    if (!email) {
      return res.status(400).json({
        success: false,
        message: '请提供邮箱地址'
      });
    }

    // 检查用户是否已存在
    const existingUser = await User.findOne({ where: { email } });
    if (existingUser) {
      return res.status(400).json({
        success: false,
        message: '该邮箱已被注册'
      });
    }

    // 生成验证码
    const verificationCode = await VerificationCode.createCode(email, 'register');

    // 发送验证码邮件
    await sendVerificationCode(email, verificationCode.code, 'register');

    res.status(200).json({
      success: true,
      message: '验证码已发送到您的邮箱'
    });
  } catch (error) {
    console.error('发送注册验证码错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
};

// 用户登录
exports.login = async (req, res) => {
  try {
    const { email, password } = req.body;

    // 验证必填字段
    if (!email || !password) {
      return res.status(400).json({
        success: false,
        message: '请提供邮箱和密码'
      });
    }

    // 查找用户
    const user = await User.findOne({ where: { email } });
    if (!user) {
      return res.status(401).json({
        success: false,
        message: '邮箱或密码错误'
      });
    }

    // 验证密码
    const isPasswordValid = await user.validatePassword(password);
    if (!isPasswordValid) {
      return res.status(401).json({
        success: false,
        message: '邮箱或密码错误'
      });
    }

    // 更新最后登录时间
    await user.update({ lastLoginAt: new Date() });

    // 生成JWT令牌
    const token = generateToken(user);

    res.status(200).json({
      success: true,
      message: '登录成功',
      data: {
        user: {
          id: user.id,
          email: user.email,
          role: user.role,
          isVerified: user.isVerified,
          virtualCoins: user.virtualCoins
        },
        token
      }
    });
  } catch (error) {
    console.error('用户登录错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
};

// 获取当前用户信息
exports.getCurrentUser = async (req, res) => {
  try {
    const user = req.user;

    res.status(200).json({
      success: true,
      data: {
        user: {
          id: user.id,
          email: user.email,
          role: user.role,
          isVerified: user.isVerified,
          virtualCoins: user.virtualCoins,
          createdAt: user.createdAt,
          lastLoginAt: user.lastLoginAt
        }
      }
    });
  } catch (error) {
    console.error('获取当前用户信息错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
};

// 发送重置密码验证码
exports.sendResetPasswordCode = async (req, res) => {
  try {
    const { email } = req.body;

    // 验证邮箱
    if (!email) {
      return res.status(400).json({
        success: false,
        message: '请提供邮箱地址'
      });
    }

    // 检查用户是否存在
    const user = await User.findOne({ where: { email } });
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '该邮箱未注册'
      });
    }

    // 生成验证码
    const verificationCode = await VerificationCode.createCode(email, 'reset_password');

    // 发送验证码邮件
    await sendVerificationCode(email, verificationCode.code, 'reset_password');

    res.status(200).json({
      success: true,
      message: '验证码已发送到您的邮箱'
    });
  } catch (error) {
    console.error('发送重置密码验证码错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
};

// 重置密码
exports.resetPassword = async (req, res) => {
  try {
    const { email, verificationCode, newPassword } = req.body;

    // 验证必填字段
    if (!email || !verificationCode || !newPassword) {
      return res.status(400).json({
        success: false,
        message: '请提供所有必填字段'
      });
    }

    // 检查用户是否存在
    const user = await User.findOne({ where: { email } });
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '该邮箱未注册'
      });
    }

    // 验证验证码
    const isCodeValid = await VerificationCode.verifyCode(email, verificationCode, 'reset_password');
    if (!isCodeValid) {
      return res.status(400).json({
        success: false,
        message: '验证码无效或已过期'
      });
    }

    // 更新密码
    user.password = newPassword;
    await user.save();

    // 发送密码重置成功邮件
    await sendPasswordResetSuccessEmail(email);

    res.status(200).json({
      success: true,
      message: '密码重置成功'
    });
  } catch (error) {
    console.error('重置密码错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
};